<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/08/07 05:20:29 $)
// $RCSfile: functions_backup.php,v $ : $Revision: 1.3 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

global $staffauth;
if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}

// Certain parts taken from phpMyAdmin and another script I found on net. I do not remember the author of other script so in case you are reading this, let me know and I will place in the required credits ;)

/**
* Generates DROP and CREATE TABLE statements
*/
function getTableDef($table)
{
    global $_SWIFT;

	$schema_create .= "DROP TABLE IF EXISTS `". $table ."`;".SWIFT_CRLF;

	$schema_create .= "CREATE TABLE `". $table ."` (".SWIFT_CRLF;		

    $result = mysql_query("SHOW FIELDS FROM `". $table ."`", $_SWIFT["backuplink"]);
    
	while($row = mysql_fetch_array($result))
    {
        $schema_create .= "   `". $row["Field"]."` ".$row["Type"];

        if(isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0")) {
            $schema_create .= " DEFAULT '$row[Default]'";
		}

        if($row["Null"] != "YES") {
            $schema_create .= " NOT NULL";
		}

        if($row["Extra"] != "") {
            $schema_create .= " ".$row["Extra"];
		}

        $schema_create .= ",".SWIFT_CRLF;
    }


    $schema_create = ereg_replace(",".SWIFT_CRLF."$", "", $schema_create);
    
	
	$result = mysql_query("SHOW KEYS FROM `". $table ."`", $_SWIFT["backuplink"]);
    
	while($row = mysql_fetch_array($result))
    {

        $kname=$row['Key_name'];
       
		if(($kname != "PRIMARY") && ($row['Non_unique'] == 0)) {
            $kname="UNIQUE|$kname";
		}

         if(!isset($index[$kname])) {
             $index[$kname] = array();
		 }

         $index[$kname][] = "`".$row['Column_name']."`";
    }

    while(list($x, $columns) = @each($index))
    {
         $schema_create .= ",".SWIFT_CRLF;

         if ($x == "PRIMARY") {
             $schema_create .= "   PRIMARY KEY (" . implode($columns, ", ") . ")";
		 } else if (substr($x,0,6) == "UNIQUE") {
            $schema_create .= "   UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
         } else {
            $schema_create .= "   KEY `". $x ."` (" . implode($columns, ", ") . ")";
		 }
    }

    $schema_create .= SWIFT_CRLF.");";

	return $schema_create;
}

/**
* Generates the actual INSERT queries
*/
function getTableContent($table, $handler)
{
	global $_SWIFT, $showcolumns;

    $result = mysql_query("SELECT * FROM $table", $_SWIFT["backuplink"]);
    $i = 0;
	echo SWIFT_CRLF;

	while($row = mysql_fetch_row($result))
    {
        $table_list = "(";

        for($j=0; $j<mysql_num_fields($result);$j++) {
            $table_list .= mysql_field_name($result,$j).", ";
		}

        $table_list = substr($table_list,0,-2);
        $table_list .= ")";

        if(isset($showcolumns)) {
            $schema_insert = "INSERT INTO `". $table . "` ". $table_list ." VALUES (";
		} else {
            $schema_insert = "INSERT INTO `". $table ."` VALUES (";
		}

        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j])) {
                $schema_insert .= " NULL,";
			} else if ($row[$j] != "") {
                $schema_insert .= " '".addslashes($row[$j])."',";
			} else {
                $schema_insert .= " '',";
			}
        }

        $schema_insert = ereg_replace(",$", "", $schema_insert);
        $schema_insert .= ")";
        
		$handler(trim($schema_insert));
        $i++;
    }

    return true;
}

/**
* Outputs the DB String returned to the handler function
*/
function dbOutput($sql_insert)
{
    global $crlf, $asfile;
    
	echo $sql_insert .";".SWIFT_CRLF;
}

/**
* Does the actual backup
*/
function doBackup($createtable = true, $compress = true, $structureonly = false)
{
	global $_SWIFT, $_DB;

	@set_time_limit(0);
	ob_start();

	// Connect to mySQL Server
	$_SWIFT["backuplink"] = mysql_connect ($_DB["hostname"], $_DB["username"], $_DB["password"]) or die ("Could not connect");
	mysql_select_db($_DB["name"], $_SWIFT["backuplink"]);

	$tables = mysql_list_tables($_DB["name"], $_SWIFT["backuplink"]);
	$num_tables = @mysql_num_rows($tables);

	echo "#############################".SWIFT_CRLF;
	echo "# SWIFT Backup System".SWIFT_CRLF;
	echo "# Date: ". date("d M Y h:i:s").SWIFT_CRLF;
	echo "#############################".SWIFT_CRLF.SWIFT_CRLF.SWIFT_CRLF;

	if ($num_tables == 0)
	{
		echo "# No Tables in Database".SWIFT_CRLF;
	} else {
		while ($i < $num_tables)
		{ 
			$table = mysql_tablename($tables, $i);

			echo SWIFT_CRLF;
			echo "# ==================================".SWIFT_CRLF;
			print "# Table Name: ". $table . SWIFT_CRLF;
			echo "# ==================================".SWIFT_CRLF;

			if ($createtable)
			{
				echo getTableDef($table).SWIFT_CRLF;				
			}
			
			if(!$structureonly)
			{		
				getTableContent($table, "dbOutput");
			}
			$i++;
		}
	}
	

	if ($compress == true && !extension_loaded("zlib"))
	{
		$compress = false;
	}

	$backupfilename = $_DB["name"] .".".date("d")."_".date("M")."_".date("Y");
	if ($compress)
	{
		header("Content-disposition: attachment; filename=\"". $backupfilename .".sql.gz\"");
		header("Content-Type: text/x-delimtext; name=\"". $backupfilename .".sql.gz\"");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		$contents = ob_get_contents();
		ob_end_clean();
	
		$crc = crc32($contents);
		$length = strlen($contents);
		$compressedcontents = gzcompress($contents);

		unset($contents);
	
		// GZIP Header
		echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
		
		// Erase last 4 bytes of compressed content
		echo substr($compressedcontents, 0, strlen($compressedcontents) - 4);
		
		echo pack('V', $crc);
		echo pack('V', $length);
		// All done!
	} else {
		header("Content-disposition: attachment; filename=\"". $backupfilename .".sql\"");		
		header("Content-Type: text/x-delimtext; name=\"". $backupfilename .".sql\"");
		header("Pragma: no-cache");
		header("Expires: 0");
		ob_end_flush();
	
	}

	mysql_close($_SWIFT["backuplink"]);

	return true;
}
?>